/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.me.stepapp;

/**
 *
 * @author Amber
 */


import java.io.IOException;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class AddLocation extends MapActivity {
    MapView mapView;
    MapController mc;
    GeoPoint p;
    Geocoder geoCoder;

    class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
        {
            super.draw(canvas, mapView, shadow);

            //---translate the GeoPoint to screen pixels---
            Point screenPts = new Point();
            mapView.getProjection().toPixels(p, screenPts);

            //---add the marker---
            Bitmap bmp = BitmapFactory.decodeResource(
                getResources(), R.drawable.pushpin);
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y-32, null);
            return true;
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.map);
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.setClickable(true);
        mapView.setBuiltInZoomControls(true);
        geoCoder = new Geocoder(this);

        Button btnSearch=(Button)findViewById(R.id.insert_add);
        btnSearch.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                TextView textAddress = (TextView)findViewById(R.id.tv_user);
            	String value = textAddress.getText().toString().trim();

            	if (value.length()==0){
                	new AlertDialog.Builder(AddLocation.this)
                    .setTitle("Error")
                    .setMessage("Please enter a valid address")
                     .setNeutralButton("Close",
                          new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dlg, int sumthin) {
                                }
                          }
                     ).show();
                }
            	else{
            		try {
                    	ProgressDialog progDialog = ProgressDialog.show(AddLocation.this, "",
                                "Finding Location...", true);
            			List<Address> addresses = geoCoder.getFromLocationName(value, 1);
            			progDialog.dismiss();
                        if (addresses.size() > 0) {
                        	displayOnMap(addresses.get(0));
                        }
                        else{
	                    	new AlertDialog.Builder(AddLocation.this)
	                        .setTitle("No Result")
	                        .setMessage("Could not find the address specified")
	                         .setNeutralButton("Close",
	                              new DialogInterface.OnClickListener() {
	                                    public void onClick(DialogInterface dlg, int sumthin) {
	                                    }
	                              }
	                         ).show();	                        }
    				} catch (IOException e) {
                    e.printStackTrace();
    				}
            	}
            }
        });

        Button btnSave=(Button)findViewById(R.id.insert_add);
        btnSave.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                if (p == null){
                	new AlertDialog.Builder(AddLocation.this)
                    .setTitle("Error")
                    .setMessage("Plase perform a search to add the location")
                    .setNeutralButton("Close",
                          new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dlg, int sumthin) {
                                }
                          }
                     ).show();
                }
                else{
                	Intent result = new Intent();
                	Double latDouble = ((double)p.getLatitudeE6())/1E6;
                	Double longDouble = ((double)p.getLongitudeE6())/ 1E6;
                	result.putExtra("lat",latDouble.toString());
                    result.putExtra("long",longDouble.toString());
                 	setResult(RESULT_OK, result);
                    finish();
                    return;
                }
            }
        });
    }

    private void displayOnMap(Address add){
		mc = mapView.getController();
		p = new GeoPoint(
		         (int) (add.getLatitude() * 1E6),
		         (int) (add.getLongitude() * 1E6));
		mc.animateTo(p);
		mc.setZoom(13);

		//---Add a location marker---
		MapOverlay mapOverlay = new MapOverlay();
		List<Overlay> listOfOverlays = mapView.getOverlays();
		listOfOverlays.clear();
		listOfOverlays.add(mapOverlay);

		mapView.invalidate();
    }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

}
